package com.seqb.common.dialect;

import com.seqb.manage.file.domain.FileDO;
import com.seqb.manage.file.service.FileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.WebEngineContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressionParser;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/15
 */
public class UploadFileProcessor extends AbstractElementTagProcessor {

    private static final int PRECEDENCE = 1000;

    public UploadFileProcessor(final String dialectPrefix, final String tagName) {
        super(TemplateMode.HTML,
                dialectPrefix,
                tagName,
                true,
                null,
                false,
                PRECEDENCE);
    }

    @Override
    protected void doProcess(ITemplateContext context, IProcessableElementTag tag, IElementTagStructureHandler structureHandler) {
        /**
         * 获取应用程序的上下文参数
         */

        WebEngineContext webEngineContext = (WebEngineContext) context;
        final String ctx = webEngineContext.getServletContext().getContextPath();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(webEngineContext.getServletContext());

        /**
         * 获取标签各属性
         */
        Long domainId = null;
        String domainFileIds = null;
        if (StringUtils.isNotEmpty(tag.getAttributeValue("domainId"))) {
            //获得Thymeleaf标准表达式解析器
            final IStandardExpressionParser parser = new StandardExpressionParser();
            //将属性值解析为Thymeleaf标准表达式
            final IStandardExpression evaluableExpression =
                    parser.parseExpression(context, tag.getAttributeValue("domainId"));
            //执行表达工式，获取domainId的值
            domainId = (Long) evaluableExpression.execute(context);
        }
        if (StringUtils.isNotEmpty(tag.getAttributeValue("domainFileIds"))) {
            //获得Thymeleaf标准表达式解析器
            final IStandardExpressionParser parser = new StandardExpressionParser();
            //将属性值解析为Thymeleaf标准表达式
            final IStandardExpression evaluableExpression =
                    parser.parseExpression(context, tag.getAttributeValue("domainFileIds"));
            //执行表达工式，获取domainId的值
            domainFileIds = evaluableExpression.execute(context).toString();
        }

        String domainName = tag.getAttributeValue("domainName");  //获取标签domainName属性
        String domainField = tag.getAttributeValue("domainField");  //获取标签domainField属性
        String domainUpdate = tag.getAttributeValue("domainUpdate");  //获取标签domainUpdate属性
        String isView = tag.getAttributeValue("isView");              //获取标签isView属性
        String accept = tag.getAttributeValue("accept"); //获取标签accept属性
        String uploadExts = tag.getAttributeValue("uploadExts");  //获取标签uploadExts属性

        if (StringUtils.isEmpty(accept)) {
            accept = "file";//所有文件
        }

        String fileName = null;
        String fileUrl = null;
        List<FileDO> fileList = null;
        if (domainId != null) {
            FileService fileService = (FileService) ac.getBean(FileService.class);
            Map params = new HashMap(16);
            params.put("offset", 0);
            params.put("limit", 1);
            params.put("domainId", domainId);
            params.put("domainName", domainName);
            params.put("domainField", domainField);
            fileList = fileService.list(params);
            if (fileList != null && fileList.size() > 0) {
                FileDO file = fileList.get(0);
                fileName = file.getFileName();
                fileUrl = file.getFileUrl();
            }
        }
        if (!StringUtils.isEmpty(domainFileIds)) {
            FileService fileService = (FileService) ac.getBean(FileService.class);
            fileList = fileService.listByIds(domainFileIds);
        }
        if (!StringUtils.isEmpty(domainUpdate)) {
            if ("false".equals(domainUpdate)) {
                domainId = null;
            }
        }
        StringBuffer html = new StringBuffer();
        html.append("<div class=\"thumbnail\">\r\n");
        html.append("   <input id=\"").append(domainField).append("_fileId\" name=\"").append(domainField).append("FileId\" class=\"form-control\" type=\"hidden\">\r\n");
        html.append("   <div class=\"caption text-center\">\r\n");
        if (fileList != null && fileList.size() > 0) {
            for (FileDO file : fileList) {
                html.append("       <a id=\"").append(file.getDomainField()).append("_fileA\" href=\"").append(ctx).append(file.getFileUrl()).append("\" target=\"_blank\"><h3 id=\"").append(file.getDomainField()).append("_fileName\">").append(file.getFileName() == null ? "" : file.getFileName()).append("</h3></a>\r\n");
                html.append("       <p id=\"").append(file.getDomainField()).append("_msg\">&nbsp;</p>\r\n");
            }
        } else {
            html.append("       <a id=\"").append(domainField).append("_fileA\" href=\"").append(ctx).append(fileUrl).append("\" target=\"_blank\"><h3 id=\"").append(domainField).append("_fileName\">").append(fileName == null ? "" : fileName).append("</h3></a>\r\n");
            html.append("       <p id=\"").append(domainField).append("_msg\">&nbsp;</p>\r\n");
        }
        if (!"true".equals(isView)) {
            html.append("       <p><button type=\"button\" class=\"layui-btn layui-btn-normal\" id=\"").append(domainField).append("_button\">上传文件</button></p>\r\n");
        }
        html.append("   </div>\r\n");
        html.append("</div>\r\n");
        html.append("<script type=\"text/javascript\">\r\n");
        html.append("   layui.use(\"upload\", function () {\r\n");
        html.append("       var upload = layui.upload;\r\n");
        html.append("       var uploadInst = upload.render({\r\n");
        html.append("           elem: \"#").append(domainField).append("_button\", //绑定元素\r\n");
        html.append("           url: ctx+\"/manage/file/file/upload\", //上传接口\r\n");
        html.append("           data: {domainId : \"").append(domainId == null ? "" : domainId).append("\",domainName : \"").append(domainName).append("\",domainField : \"").append(domainField).append("\"},\r\n");
        html.append("           accept: \"" + accept + "\",\r\n");
        if (!StringUtils.isEmpty(uploadExts)) {
            html.append("           exts: \"").append(uploadExts).append("\",\r\n");
        }
        html.append("           done: function (r) {\r\n");
        html.append("               if(r.code==0){\r\n");
        html.append("                   $(\"#").append(domainField).append("_fileA\").attr(\"href\",ctx+r.fileUrl);\r\n");
        html.append("                   $(\"#").append(domainField).append("_fileName\").html(r.fileName);\r\n");
        html.append("                   $(\"#").append(domainField).append("_fileId\").val(r.fileId);\r\n");
        html.append("                   $(\"#").append(domainField).append("_msg\").html(r.msg);\r\n");
        html.append("               }\r\n");
        html.append("               else{\r\n");
        html.append("                   this.error(r);\r\n");
        html.append("               }\r\n");
        html.append("           },\r\n");
        html.append("           error: function (r) {\r\n");
        html.append("               $(\"#").append(domainField).append("_fileA\").attr(\"href\",\"#\");\r\n");
        html.append("               $(\"#").append(domainField).append("_fileName\").html(\"\");\r\n");
        html.append("               $(\"#").append(domainField).append("_fileId\").val(\"\");\r\n");
        html.append("               $(\"#").append(domainField).append("_msg\").html(r.msg);\r\n");
        html.append("           }\r\n");
        html.append("       });\r\n");
        html.append("   });\r\n");
        html.append("</script>\r\n");

        /**
         * 创建DOM元素模型
         */
        final IModelFactory modelFactory = context.getModelFactory();
        final IModel model = modelFactory.createModel();

        model.add(modelFactory.createText(html.toString()));
        /*
         * Instruct the engine to replace this entire element with the specified model.
         * 通过 structureHandler 修改tag标签的内容
         */
        structureHandler.replaceWith(model, false);
    }

}
